var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const { expressjwt: expressJwt } = require('express-jwt');

const {secretOrPrivateKey} = require('./config')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 设置 CORS 解决跨域
app.use('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); // 表示允许哪些网站访问，上线后应该直接指定ip而不应该 *
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With');
  res.header('Access-Control-Allow-Credentials', 'true');//和客户端对应，必须设置以后，才能接收cookie.

  next();
})

// 权限拦截
app.use(expressJwt({
  secret: secretOrPrivateKey, // 与 生成 token 的 密钥 相同
  algorithms: ['HS256'], // 与生成 token 的加密算法一致
}).unless({ // 路由白名单，以下路由不受验证，可以直接写路径，也可以是正则匹配
  path: ['/', '/users/login']
}))

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // 权限错误处理
  if(err.name === 'UnauthorizedError') {
    res.status(401).json({
      errCode: 401,
      errMsg: 'UnauthorizedError'
    }) // 这里响应状态吗 401，表示无权限访问
    return;
  }

  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
